<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'
import router from '@/router'
import { getSearchSuggest } from '@/api/index'
import { debounce } from 'lodash'

// 输入框初始化
const value = ref('')
// 搜索的电影列表
const searchlist = ref(null)
// 搜索结果数量
const movienum = ref(0)
// 搜索的影院列表
const cinemaslist = ref(null)
// 搜索结果数量
const cinemasnum = ref(0)

const MAX_HISTORY = 10 // 最大历史记录数量

const hisSearch = (data) => {
  onSearch(data)
  setTimeout(() => {
    value.value = data
  }, 800)
}
// 搜索方法
const onSearch = debounce((val) => {
  if (val) {
    // 显示搜索提示
    // showToast(val)

    // 获取当前的历史记录
    let searchHistory = JSON.parse(localStorage.getItem('SearchHistory')) || []

    // 检查历史记录中是否已经存在该项
    const index = searchHistory.indexOf(val)

    // 如果历史记录中存在相同的搜索项，先删除它
    if (index !== -1) {
      searchHistory.splice(index, 1) // 删除旧的记录
    }

    // 将新的搜索项添加到历史记录的最前面
    searchHistory.unshift(val)

    // 保证历史记录最多有 MAX_HISTORY 条
    if (searchHistory.length > MAX_HISTORY) {
      searchHistory.pop() // 删除最旧的记录
    }

    // 更新本地存储
    localStorage.setItem('SearchHistory', JSON.stringify(searchHistory))

    getSearchSuggest(val).then((res) => {
      if (res && res.data && res.data.movies && Array.isArray(res.data.movies.list)) {
        // console.log('aaa', res.data)
        searchlist.value = res.data.movies.list
        movienum.value = res.data.movies.total || 0
      }
      if (res && res.data && res.data.cinemas && Array.isArray(res.data.cinemas.list)) {
        cinemaslist.value = res.data.cinemas.list
        cinemasnum.value = res.data.cinemas.total || 0
      }
    })
  }
}, 500) // 500 毫秒的防抖延迟
const onCancel2 = () => {
  searchlist.value = ''
  cinemaslist.value = ''
}
const onCancel = () => {
  router.back()
}
const jumpsearchmovie = (val) => {
  // console.log('222', val)
  router.push({ name: 'searchmovie', query: { val } })
}
const jumpsearchcinema = (val) => {
  // console.log('222', val)
  router.push({ name: 'searchcinema', query: { val } })
}
// 搜索历史
// 初始化搜索历史，读取 localStorage 的数据
const searchHistory = ref(JSON.parse(localStorage.getItem('SearchHistory')) || [])

// 删除历史记录的方法
const removeHistory = (index) => {
  // 从历史记录中移除指定项
  searchHistory.value.splice(index, 1)

  // 更新本地存储
  localStorage.setItem('SearchHistory', JSON.stringify(searchHistory.value))
}

// 待映
const searchSuggest = ref(null)
getSearchSuggest(value).then((res) => {
  // console.log('getSearchSuggest', res.data.movies.list)
  searchSuggest.value = res.data.movies.list
})

// 影院
function ToCinema(id) {
  router.push({ path: '/cinemaDetails', query: { id: id } })
}

// 跳转到电影详情页
const film=(movie)=>{
    router.push({
        path: '/fil',
        query: {
            movieId: movie.id
        }
    })
}
</script>

<template>
  <div class="search">
    <header>
      <div class="back" @click="$router.back()">
        <van-icon name="arrow-left" size="30" color="#fff" />
      </div>
      <div class="title">猫眼电影</div>
    </header>
    <div class="search_input">
      <form action="/" style="width: 100%">
        <!-- <van-search v-model="value"  @cancel="onCancel"  show-action placeholder="搜电影、搜影院"  /> -->
        <van-search
          v-model="value"
          placeholder="搜电影、搜影院"
          @clear="onCancel2"
          autofocus
          @update:model-value="onSearch"
          clear-icon="https://obj.pipi.cn/festatic/common/image/071cb4dfad74d9c83681efde4c13df46.png"
          @cancel="onCancel"
          show-action
        />
      </form>
    </div>
    <template v-if="searchlist || cinemaslist">
      <!-- 电影列表 -->
      <div class="list" v-if="searchlist">
        <div class="list_title">电影/电视剧/综艺</div>
        <hr class="custom-hr" />
        <div @click="film(movie)" v-for="movie in searchlist" :key="movie.id" class="listItem">
          <div>
            <van-image width="64rem" height="96rem" fit="cover" :src="movie.img" />
          </div>
          <div class="content">
            <div class="title-box">
              <span class="name text-ellipsis">{{ movie.nm }}</span>
              <span class="icon" v-if="movie.version === 'v3d imax'"
                ><van-image
                  width="60rem"
                  height="auto"
                  fit="cover"
                  class="img"
                  src="https://obj.pipi.cn/festatic/apollo/resources/images/search/img/base64/v3dimax.png"
              /></span>
              <span class="icon" v-else-if="movie.version === 'v2d imax'"
                ><van-image
                  width="60rem"
                  height="auto"
                  class="img"
                  fit="cover"
                  src="https://obj.pipi.cn/festatic/apollo/resources/images/search/img/base64/v2dimax.png"
              /></span>
            </div>
            <p class="text-ellipsis">{{ movie.enm }}</p>
            <p class="text-ellipsis">{{ movie.cat }}</p>
            <p class="text-ellipsis">{{ movie.rt }}</p>
            <div class="buy" v-if="movie.showStateButton">购票</div>
          </div>
          <div>
            <p v-if="movie.sc">
              <span class="score">{{ movie.sc }}</span
              >分
            </p>
            <p v-else>暂无评分</p>
          </div>
        </div>
        <div class="list_title2" @click="jumpsearchmovie(value)">
          查看全部{{ movienum }}部影视剧
        </div>
      </div>
      <!-- 影院列表 -->
      <div class="cinema" v-if="cinemaslist">
        <div class="cinema_title">影院</div>
        <hr class="custom-hr" />
        <div v-for="cinema in cinemaslist" :key="cinema.id" class="cinemaItem" @click="ToCinema(cinema.id)">
          <div class="content">
            <div class="title-box">
              <h3 class="text-ellipsis">{{ cinema.nm }}</h3>
              <p class="text-ellipsis">{{ cinema.sellPrice }}</p>
            </div>
            <p class="text-ellipsis">{{ cinema.addr }}</p>
            <div class="icon">
              <span v-if="cinema.sell" class="green">座</span>
              <span v-if="cinema.vipDesc" class="green">社比全景声音厅</span>
              <span v-if="cinema.allowRefund" class="green">退</span>
              <span v-if="cinema.endorse" class="green">改签</span>
              <span v-if="cinema.snack" class="yellow">小吃</span>
            </div>
          </div>
        </div>
        <div class="cinema_title2" @click="jumpsearchcinema(value)">
          查看全部{{ cinemasnum }}部影视剧
        </div>
      </div>
    </template>
    <template v-else>
      <div class="search-history">
        <ul>
          <!-- 遍历搜索历史 -->
          <li v-for="(history, index) in searchHistory" :key="index" @click="hisSearch(history)">
            <div class="searcch-title">
              <van-icon color="#cecece" name="clock-o" />
              <span>{{ history }}</span>
            </div>
            <!-- 删除按钮 -->
            <van-icon color="#cecece" name="cross" @click="removeHistory(index)" />
          </li>
        </ul>
      </div>
    </template>
  </div>
</template>

<style lang="less" scoped>
.serach {
  background-color: #f5f5f5;
  box-sizing: border-box;
}
header {
  background-color: #fff;
  border-bottom: 1px solid #00000018;
  position: relative;

  .back {
    position: absolute;
    left: 10rem;
    top: 12rem;
  }

  .title {
    background-color: #e54847;
    font-size: 18rem;
    text-align: center;
    height: rem;
    padding: 0.12rem;
    color: #fff;
    height: 50rem;
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
}

.search_input {
  display: flex;
  align-items: center;
  padding: 0.16rem 0 0.16rem 0.2rem;
  background-color: #f5f5f5;
  border-bottom: 1rem solid #e5e5e5;
  position: relative;
  z-index: 1;
}
.custom-hr {
  border: 0; /* 去掉默认的边框 */
  border-top: 1px solid #bababa48; /* 设置水平线的粗细和颜色 */
}
.list {
  background-color: #fff;
  padding: 12rem;
  .list_title {
    font-size: 17rem;
    color: #999;
    padding: 9rem 3rem;
  }
  .list_title2 {
    font-size: 17rem;
    padding: 10rem 0;
    color: #ef4238;
    text-align: center;
    font-weight: 500;
  }
  .listItem {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 8rem 0;
    border-bottom: 1px solid #00000018;
    position: relative;
    .buy {
      position: absolute;
      bottom: 25rem;
      right: 0;
      font-size: 14rem;
      font-weight: 500;
      color: white;
      background-color: #f60026;
      padding: 6rem 12rem;
      border-radius: 20rem;
    }
    .content {
      width: 60%;

      .title-box {
        display: flex;
        align-items: center;
        .name {
          display: block;
          max-width: 80%;
          font-size: 17rem;
          color: #333;
          font-weight: 700;
          margin: 6rem 0;
        }
        .icon {
          margin-left: 10rem;
        }
      }

      p {
        font-size: 13rem;
        color: #666;
        margin: 0;
        margin-top: 6rem;
      }
    }

    p {
      font-size: 12rem;
      color: #faaf00;

      .score {
        font-weight: 700;
        font-size: 15rem;
        margin-left: 4rem;
      }
    }
  }
}

.cinema {
  background-color: #fff;
  padding: 12rem;
  .cinema_title {
    font-size: 17rem;
    color: #999;
    padding: 9rem 3rem;
  }
  .cinema_title2 {
    font-size: 17rem;
    padding: 10rem 0;
    color: #ef4238;
    text-align: center;
    font-weight: 500;
  }

  .cinemaItem {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 8rem 0;
    border-bottom: 1px solid #00000018;

    .content {
      .title-box {
        display: flex;
        align-items: center;
        h3 {
          font-size: 17rem;
          color: #333;
          font-weight: 700;
          margin: 6rem 0;
        }
        p {
          font-size: 17rem;
          color: #e54847;
          margin-left: 10rem;
          &::after {
            content: '元起';
            font-size: 11rem;
            color: #999;
          }
        }
      }
      .icon {
        font-size: 11rem;
        margin-top: 10rem;
        span {
          display: inline-block;
          margin-bottom: 10rem;
          padding: 0rem 4rem;
          border: 0.02rem solid;
          margin-right: 10rem;
          &.green {
            border-color: #589daf;
            color: #589daf;
          }
          &.yellow {
            color: #f90;
            border-color: #f90;
          }
        }
      }
      p {
        font-size: 13rem;
        color: #999;
        margin: 0;
        margin-top: 6rem;
      }
    }

    p {
      font-size: 12rem;
      color: #999;

      .score {
        font-weight: 700;
        color: #faaf00;
        font-size: 15rem;
        margin-left: 4rem;
      }
    }
  }
}
// 单行文本溢出
.text-ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.search-history {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 8px;
  font-size: 18rem;
  ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    margin-bottom: 8px;
    background-color: #fff;
    border-radius: 4px;
    border-bottom: 1px solid #f5f5f5;
    .searcch-title {
      display: flex;
      > span {
        font-size: 14rem;
        margin-left: 10rem;
      }
    }
  }
}
</style>